package com.kfm.base.thread.day02;

import java.time.LocalDateTime;

public class Demo07{


    public static void main(String[] args) {
        Cook cook = Cook.getInstance();

        Thread make = new Maker(cook, "张厨子");
//        Thread make2 = new Maker(cook, "李厨子");
        Eater eat = new Eater(cook, "八戒");
        Eater eat2 = new Eater(cook, "文博");
        Eater eat3 = new Eater(cook, "秦爽");

        make.start();
//        make2.start();
        eat.start();
        eat2.start();
        eat3.start();

    }
}

class Maker extends Thread {

    Cook cook;

    public Maker(Cook cook, String name){
        super(name);
        this.cook = cook;
    }

    @Override
    public void run(){
        while (true){
            cook.make();
        }
    }
}

class Eater extends Thread {
    Cook cook;

    public Eater(Cook cook, String name){
        super(name);
        this.cook = cook;
    }

    public void run(){
        while (true){
            cook.eat();
        }
    }
}
class Cook {

    // 面包
    private String name;

    private final static Cook cook = new Cook();

    private Cook(){}

    public static Cook getInstance(){
        return cook;
    }

    public synchronized void make(){
        if (name != null){
            try {
                System.out.println(Thread.currentThread().getName() + " 睡了 ");
                wait();
                System.out.println(Thread.currentThread().getName() + " 醒了 ");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        try {
            // 模拟做面包的过程
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        name = LocalDateTime.now().toString();
        notify(); // 唤醒等待的线程
        System.out.println(Thread.currentThread().getName() + "做了一个面包  " + name);
    }

    public synchronized void eat(){
        if (name == null){
            try {
                System.out.println(Thread.currentThread().getName() + " 睡了 ");
                wait();
                System.out.println(Thread.currentThread().getName() + " 醒了 ");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        } else {
            try {
                // 模拟吃的时间
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "吃了 " + name);
            name = null;
            notifyAll();// 唤醒所有等待的线程（确保厨子能被唤醒）
        }

    }
}
